<template>
    <div class="default-main ba-table-box">
        <el-alert class="ba-table-alert" v-if="baTable.table.remark" :title="baTable.table.remark" type="info" show-icon />
  
        <!-- 表格顶部菜单 -->
        <!-- 自定义按钮请使用插槽，甚至公共搜索也可以使用具名插槽渲染，参见文档 -->
        <TableHeader
            :buttons="['refresh', 'comSearch', 'quickSearch', 'columnDisplay']"
            quick-search-placeholder="流程编号"
        >
          <el-button class="table-header-operate" type="danger" @click="batch(0)" v-if="params.type == 1">
              <Icon name="el-icon-Close" color="#8595F4" size="20" />
              <span class="table-header-operate-text">{{ t('不同意') }}</span>
          </el-button>
  
          <el-button class="table-header-operate" type="primary" @click="batch(1)" v-if="params.type == 1">
              <Icon name="el-icon-Check" color="#8595F4" size="20" />
              <span class="table-header-operate-text">{{ t('同意') }}</span>
          </el-button>
      </TableHeader>
  
        <!-- 表格 -->
        <!-- 表格列有多种自定义渲染方式，比如自定义组件、具名插槽等，参见文档 -->
        <!-- 要使用 el-table 组件原有的属性，直接加在 Table 标签上即可 -->
        <Table ref="tableRef"
            :show-summary="wf_type == '1'"
            :summary-method="tableSummary"
            @selection-change="handleSelectionChange"  v-loading="loading"></Table>
        <!-- 表单 -->
          <Detail />
    </div>
  </template>
  
  <script setup lang="ts">
  import { onMounted, provide, ref, h } from 'vue'
  import {  ElMessageBox } from 'element-plus'
  import { useRoute } from 'vue-router'
  import { useI18n } from 'vue-i18n'
  import { baTableApi } from '/@/api/common'
  import { defaultOptButtons } from '/@/components/table'
  import TableHeader from '/@/components/table/header/index.vue'
  import Table from '/@/components/table/index.vue'
  import baTableClass from '/@/utils/baTable'
  import Detail from './detail.vue'
  import { wfAudit } from '/@/api/backend/index'
  
  defineOptions({
    name: 'project',
  })
  const { params } = useRoute()
  const { t } = useI18n()
  const tableRef = ref()
  const optButtons: OptButton[] = defaultOptButtons([])
  const buttons: OptButton[] = [
      {
          render: 'tipButton',
          name: 'info',
          title: '详情',
          text: '详情',
          type: 'success',
          icon: '',
          class: 'table-row-info',
          disabledTip: false,
          click: (row: TableRow, field: TableColumn) => {
              doAction(row, 'detail')
          },
      },
      {
          render: 'tipButton',
          name: 'info',
          title: '不同意',
          text: '不同意',
          type: 'danger',
          icon: '',
          class: 'table-row-info',
          disabledTip: false,
          display(row, field) {
              return params.type == 1
          },
          click: (row: TableRow, field: TableColumn) => {
              batch(0, [row.id])
          },
      },
      {
          render: 'tipButton',
          name: 'info',
          title: '同意',
          text: '同意',
          type: 'primary',
          icon: '',
          class: 'table-row-info',
          disabledTip: false,
          display(row, field) {
              return params.type == 1
          },
          click: (row: TableRow, field: TableColumn) => {
              batch(1, [row.id])
          },
      },
  ]
  const wf_type = ref(params.type)
  // 新按钮合入到默认的按钮数组
  const optBtns = [...buttons, ...optButtons]
  
  /**
  * baTable 内包含了表格的所有数据且数据具备响应性，然后通过 provide 注入给了后代组件
  */
  const baTable = new baTableClass(
      new baTableApi('/admin/workflow.Workflow/'),
      {
          pk: 'id',
          column: [
              { type: 'selection', align: 'center', operator: false },
              { label: '项目名称', width: 160, prop: 'name', align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE', sortable: 'custom',render: 'customTemplate', customTemplate:(row: TableRow, field: TableColumn, value: any, column: TableColumnCtx<TableRow>, index: number) => {
                return row.project_name;
              }},
              { label: '类别名称', width: 85, prop: 'template_name', align: 'center', sortable: false },
              { label: '总额', width: 80,  operator: false, render: 'customTemplate', customTemplate:(row: TableRow, field: TableColumn, value: any, column: TableColumnCtx<TableRow>, index: number) => {
                let content = JSON.parse(row.content)
                let html = 0
                let feeitems = []
                try {
                    feeitems = JSON.parse(content.feeitems)
                } catch {
                    feeitems = []
                }
                feeitems.forEach((item: any) => {
                    html += Number(item.amount)
                })                
                return html;
              }},
              { label: '费用项目', minWidth: 300,  operator: false, render: 'customTemplate', customTemplate:(row: TableRow, field: TableColumn, value: any, column: TableColumnCtx<TableRow>, index: number) => {
                let content = JSON.parse(row.content)
                let html = ''
                let feeitems = []
                try {
                    feeitems = JSON.parse(content.feeitems)
                } catch {
                    feeitems = []
                }
                feeitems.forEach((item: any) => {
                    html += `<div class="table-feeitem"><span>${item.feeitem_name}</span> <span>${ item.amount }</span></div>`
                })                
                return html;
              }},
              { label: '供应商', width: 180,  operator: false, render: 'customTemplate', customTemplate:(row: TableRow, field: TableColumn, value: any, column: TableColumnCtx<TableRow>, index: number) => {
                let content = JSON.parse(row.content)
                let html = `${content.supplier?.company_name??""}`;               
                return html;
              }},
              { label: '流程类型', prop: 'flow_model',width: 100, align: 'center', render: 'tag', operator: 'eq', sortable: false, replaceValue: { '1': '报销申请', '2': '预支申请', '3': '付款申请', '4': '预算申请' } },
              { label: '申请人', prop: 'creator_name', width: 100, align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE', sortable: false },
              { label: '申请时间', prop: 'creator_time', width: 160, align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE', sortable: false },
              { label: '流程编号', prop: 'flow_no', width: 160,align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE', sortable: false },
              { label: '流程状态', prop: 'state', width: 110, align: 'center', operatorPlaceholder: t('Fuzzy query'), render: 'tag', operator: 'eq', sortable: 'custom', replaceValue: {'0':'未提审' , '1': '审核中', '2': '审核拒绝', '3': '审核通过' }, custom: {'0':'' , '1': '', '2': 'danger', '3': 'success' } },
              { label: '当前审批人', prop: 'audit_name', width: 100, align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE', sortable: false },
              { label: '审批时间', prop: 'update_time', width: 160, align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE', sortable: false },
              { label: '完成时间', prop: 'complete', width: 160, align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE', sortable: false },
              { label: t('Operate'), align: 'center', width: 100, fixed:'right', render: 'buttons', buttons: optBtns, operator: false },
          ],
          filter: {
              searchType: params.type,
              limit: 50
          },
          dblClickNotEditColumn: ['all'],
      },
      {
          defaultItems: { date: null },
      }
  )
  
  provide('baTable', baTable)
  
  onMounted(() => {
    baTable.table.ref = tableRef.value
    baTable.mount()
    baTable.getIndex()?.then(() => {
        baTable.initSort()
        baTable.dragSort()
    })
  })
  
  const doAction = (row: TableRow, opt: string) => {
    baTable.form.items! = {...row};
    baTable.form.operate = opt
  }
  let auditForm = {
      msg: '',
      audit_state: '',
      node_id: 0,
      flow_id: 0,
      node_step: 0,
      node_type: 0,
      scope_id: 0,
      scope_name: '',
      attachs: '',
      flow_no: ''
  }
  let loading = ref(false)
  
  const batch = (audit_state: number, ids?:[]) => {
      const selectionIds = ids == undefined ? baTable.getSelectionIds() : ids
      if(selectionIds.length == 0) return false
      ElMessageBox.confirm(
          '确认操作?',
          '提示',
          {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
          }
      ).then(() => {
          const functions: any[] = []
          baTable.table.data?.forEach((item: any) => {
              if(selectionIds.indexOf(item.id) > -1){
                  functions.push(wfAudit({
                      msg: '',
                      audit_state: audit_state,
                      node_id: item.now_node.node_id,
                      flow_id: item.now_node.flow_id,
                      node_step: item.now_node.node_step,
                      node_type: item.now_node.node_type,
                      scope_id: item.now_node.scope_id,
                      scope_name: item.now_node.scope_name,
                      attachs: '',
                      flow_no: item.flow_no
                  }))
              }
          })
          loading.value = true
          Promise.all(functions).then(() => {
              
          }).finally(() => {
              baTable.getIndex()
              loading.value = false
          })
      })
  }
  let selDatas = []
    let lastTable = 'wf'
  const handleSelectionChange = (val: any[]) => {
    selDatas = val
    console.log('handleSelectionChange', val)
    // allowExport.value = val.length == 0
    let sum = 0
    let dics = {
        reimbursement: {field: 'amount', tableIndex:2, colIndex: 7},
        advance: {field: 'amount', tableIndex:3, colIndex: 5},
        payment: {field: 'pay_amount', tableIndex:4, colIndex: 7},
        wf: {field: 'amount', tableIndex:4, colIndex: 7},
    }
    console.log('selDatas', selDatas)
    selDatas.forEach((item: any) => {
        try {
            let content = JSON.parse(item['content']);
            sum += content['amount'] !== undefined ? Number(content['amount']) : (content['pay_amount'] !== undefined ? Number(content['pay_amount']) : 0)
        } catch {

        }
        
    })
    const ele = document.querySelector(`.el-table__footer-wrapper > table  tfoot > tr > td .cell .cell2`)
    setTimeout(() => {
        ele.innerHTML = sum
    }, 50)
}

const tableSummary = (param: any) => {
    const { columns, data } = param
    const sums: string[] = []
    sums[0] = '合计'
    sums[1] = h('div', {class: "cell1"}, "")
    sums[2] = h('div', {class: "cell2"}, "")
    sums[3] = h('div', {class: "cell3"}, "")
    sums[8] = h('div', {class: "cell8"}, "")
    return sums
}
  </script>
  
<style scoped lang="scss">
    
</style>
  